<template>
  <div class="app-container">
    <div class="card-box">
      <el-button type="primary" @click="handleToAdd">添加账单明细</el-button>
    </div>
    <div class="card-box">
      <el-table
        v-loading="accountStore.loading.list || accountStore.loading.update"
        :data="accountStore.list"
        row-id="id"
      >
        <el-table-column label="ID" prop="id" />
        <el-table-column label="用户">
          <template #default="{ row }">
            {{ row.account.username }}
          </template>
        </el-table-column>
        <el-table-column label="充值金额" prop="amount" />
        <el-table-column label="类型">
          <template #default="{ row }">
            <el-tag v-if="row.type == 'income'" type="success">入账</el-tag>
            <el-tag v-if="row.type == 'outgoing'" type="danger">支出</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleToEdit(row)">编辑</el-button>
            <el-popconfirm title="是否继续删除？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="danger" link>删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="params.page"
        v-model:page-size="params.size"
        style="margin-top: 10px"
        background
        :total="accountStore.totalCount"
        @change="accountStore.fetchRechargeList(params)"
      />
    </div>
    <Form
      v-model="visible"
      :type="formType"
      :form="currentForm"
      @confirm="accountStore.fetchRechargeList(params)"
    />
  </div>
</template>

<script setup lang="ts">
import { type AccountListQuery, type AccountForm, type AccountItemType } from "@/api/user/account";
import { useAccountStoreHook } from "@/store/modules/user/account";
import Form from "./components/form.vue";
import type { FormType } from "./components/form.vue";

const accountStore = useAccountStoreHook();

const visible = ref(false);

const formType = ref<FormType>("add");

const currentForm = ref<AccountForm>({
  id: 0,
  account: "",
  type: "income",
  amount: "",
  remark: "",
});

const params = reactive<AccountListQuery>({
  page: 1,
  size: 10,
});

function handleToAdd() {
  formType.value = "add";
  visible.value = true;
}

async function handleDelete(row: AccountItemType) {
  await accountStore.fetchDeleteRecharge(row.id);
  await accountStore.fetchRechargeList(params);
}

function handleToEdit(row: AccountItemType) {
  formType.value = "edit";
  currentForm.value = {
    id: row.id,
    account: row.account.id as unknown as string,
    type: row.type,
    amount: row.amount,
    remark: row.remark,
  };
  visible.value = true;
}

onMounted(() => {
  accountStore.fetchRechargeList(params);
});
</script>

<style scoped lang="scss"></style>
